<template>
  <div>
    <a-modal
      v-model="visible"
      title="选择需要的增值服务"
      :width="1800"
      :maskClosable="false"
      @ok="onSubmit"
      @cancel="onCancel"
    >
      <a-alert type="error" message="增值项在使用过程中出现问题请刷新页面再试!!!!!"></a-alert>
      <p></p>
      <a-spin :spinning="loading">
        <a-table
          bordered
          size="middle"
          :row-key="(record, index) => index"
          :columns="zxColumns"
          :data-source="zxData"
          :pagination="false"
          :scroll="{ y: 700, x: 1800 }"
        >
          <template slot="xu" slot-scope="text,record,index">
            {{ index + 1 }}
          </template>
          <template slot="action" slot-scope="text,record,index">
            <a-button :disabled="extCacheId === ''" size="small" type="danger" @click="delColumn(index)">删</a-button>
            <a-button size="small" type="primary" @click="clearColumn(index)">清</a-button>
          </template>
          <template slot="cbx" slot-scope="text,record,index">
            <a-checkbox :checked="addForm['ext_' + index + '_' + text.ext_id]" @change="(e) => onChange(e,index,text.ext_id,text.price)">{{text.name}} * {{text.price}}</a-checkbox>
          </template>
          <template slot="ipt" slot-scope="text,record,index">
            <a-input-number
              :min="0"
              style="width:100px"
              v-model="addForm['ext_' + index + '_' + text.ext_id]"
              :default-value="addForm['ext_' + index + '_' + text.ext_id]"
              @change="(value) => onNumberChange(value,text.ext_id,index)"
              @blur="onBlur(text.ext_id,index,text.price)"
              @focus="onFocus(text.ext_id, index)"
            >
            </a-input-number> * {{text.price}}
          </template>
          <template slot="row_total" slot-scope="text,record">
            <div class="total">{{parseInt(record.check_total) + parseInt(record.ipt_total)}}</div>
          </template>
          <template slot="footer">
            <div style="text-align: right">
              <a-spin :spinning="loading5">
                附加项官费合计: {{extAmount + extAmount2}}
              </a-spin>
            </div>
          </template>
        </a-table>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
  // import { pinyin } from 'pinyin-pro'
  import { getAddExtCache, getAddItem, postAddExtCache } from '@/api/contract'

  export default {
    props: {
      businessId: {
        type: String,
        default: ''
      },
      businessName: {
        type: String,
        default: ''
      },
      businessNum: {
        type: String,
        default: ''
      },
      cacheId: {
        type: String,
        default: ''
      },
      extCacheId: {
        type: String,
        default: ''
      }
    },
    name: 'ExtModal',
    data () {
      return {
        visible: true,
        loading: true,
        addForm: {},
        beforeForm: {},
        zxColumns: [
          {
            title: '序号',
            scopedSlots: { customRender: 'xu' },
            width: '80px'
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
            width: '100px'
          },
          {
            title: '业务名称',
            dataIndex: 'business_name'
          }
        ],
        zxData: [],
        typeOpts: {},
        pagination: {},
        extOpts: {},
        extAmount: 0,
        extAmount2: 0,
        loading5: false
      }
    },
    created () {
      this.getAddExt()
    },
    methods: {
      getAddExt () {
        const app = this
        const total = {}
        const arr = []
        getAddItem(app.businessId).then(res => {
          app.typeOpts = res.result.typeOpts
          app.extOpts = res.result.data
          for (let i = 0; i < res.result.data.length; i++) {
            const data = {}
            data['title'] = res.result.data[i].name
            data['dataIndex'] = 'ext' + '_' + i + '_' + res.result.data[i].ext_id
            if (res.result.data[i].type === 'count') data['scopedSlots'] = { customRender: 'ipt' }
            else data['scopedSlots'] = { customRender: 'cbx' }
            app.zxColumns.push(data)
          }
          total['title'] = '小计'
          total['scopedSlots'] = { customRender: 'row_total' }
          total['fixed'] = 'right'
          total['width'] = '150px'
          arr.push(total)
          app.zxColumns = app.zxColumns.concat(arr)
        }).finally(() => {
          const params = {}
          params['cache_id'] = app.cacheId
          params['ext_cache_id'] = app.extCacheId
          getAddExtCache(params).then(res => {
            if (res.result.values === '') {
              for (let i = 0; i < app.businessNum; i++) {
                const arr = {}
                arr['business_name'] = app.businessName
                arr['check_total'] = 0
                arr['ipt_total'] = 0
                for (let j = 0; j < app.extOpts.length; j++) {
                  arr['ext_' + j + '_' + app.extOpts[j].ext_id] = app.extOpts[j]
                  if (app.extOpts[j].type === 'count') {
                    app.addForm['ext_' + i + '_' + app.extOpts[j].ext_id] = 0
                    app.beforeForm['ext_' + i + '_' + app.extOpts[j].ext_id] = 0
                  } else {
                    app.addForm['ext_' + i + '_' + app.extOpts[j].ext_id] = false
                  }
                }
                app.zxData.push(arr)
              }
            } else {
              const arr = res.result.info
              const arr2 = {}
              // const arr3 = []
              app.addForm = res.result.values
              for (const k in arr) {
                arr[k].check_total = parseInt(arr[k].check_total)
                arr[k].ipt_total = parseInt(arr[k].ipt_total)
              }
              if (arr.length > app.businessNum) {
                arr.splice(arr.length, arr.length - app.businessNum)
              } else {
                for (let i = arr.length; i < app.businessNum; i++) {
                  arr2['business_name'] = app.businessName
                  arr2['check_total'] = 0
                  arr2['ipt_total'] = 0
                  for (let j = 0; j < app.extOpts.length; j++) {
                    arr2['ext_' + j + '_' + app.extOpts[j].ext_id] = app.extOpts[j]
                    if (app.extOpts[j].type === 'count') {
                      app.addForm['ext_' + i + '_' + app.extOpts[j].ext_id] = 0
                      app.beforeForm['ext_' + i + '_' + app.extOpts[j].ext_id] = 0
                    } else {
                      app.addForm['ext_' + i + '_' + app.extOpts[j].ext_id] = false
                    }
                  }
                  arr.push(arr2)
                }
              }
              app.zxData = arr
            }
          })
          app.loading = false
        })
      },
      onSubmit () {
        const app = this
        const data = {}
        const data2 = {}
        let total = 0
        for (const k in app.addForm) {
          //
          if (typeof app.addForm[k] === 'number') {
            data['bs[' + app.businessId + '][' + 'key' + k.match(/_(\S*)_/)[1] + '][' + k.substring(k.lastIndexOf('_') + 1) + '][count]'] = app.addForm[k]
          } else if (typeof app.addForm[k] === 'boolean') {
            if (app.addForm[k]) {
              data['bs[' + app.businessId + '][' + 'key' + k.match(/_(\S*)_/)[1] + '][' + k.substring(k.lastIndexOf('_') + 1) + '][count]'] = 1
            }
          }
        }
        for (const k in app.zxData) {
          total += app.zxData[k].check_total + app.zxData[k].ipt_total
        }
        data2['ext[values]'] = app.addForm
        data2['ext[info]'] = app.zxData
        data2['ext[price]'] = total
        postAddExtCache(data2, app.cacheId, app.extCacheId).then(res => {
          if (res.status === 0) {
            app.onCancel()
            app.$emit('change', data, app.businessId)
          } else {
            app.$warning({
              title: res.msg
            })
          }
        })
      },
      onCancel () {
        this.visible = false
        this.$emit('cancel', this.visible)
      },
      onNumberChange (value, id, index) {
        const app = this
        app.loading = true
        app.addForm['ext_' + index + '_' + id] = value
        app.$set(this.addForm, `ext_${index}_${id}`, value)
        app.extAmount2 = 0
        for (const k in app.zxData) {
          app.extAmount2 = app.extAmount2 + app.zxData[k].ipt_total
        }
        app.loading = false
      },
      onBlur (id, index, price) {
        const app = this
        if (app.beforeForm['ext_' + index + '_' + id] === 0) {
          app.zxData[index].ipt_total += app.addForm['ext_' + index + '_' + id] * price
        } else {
          if (app.beforeForm['ext_' + index + '_' + id] > app.addForm['ext_' + index + '_' + id]) {
            app.zxData[index].ipt_total -= (app.beforeForm['ext_' + index + '_' + id] - app.addForm['ext_' + index + '_' + id]) * price
          } else {
            app.zxData[index].ipt_total += (app.addForm['ext_' + index + '_' + id] - app.beforeForm['ext_' + index + '_' + id]) * price
          }
        }
        app.extAmount2 = app.zxData[index].ipt_total
      },
      onFocus (id, index) {
        this.beforeForm['ext_' + index + '_' + id] = this.addForm['ext_' + index + '_' + id]
      },
      onChange (e, index, id, price) {
        const app = this
        app.loading = true
        if (e.target.checked) {
          app.zxData[index].check_total = Number(app.zxData[index].check_total + parseInt(price))
        } else {
          app.zxData[index].check_total = Number(app.zxData[index].check_total - parseInt(price))
        }
        app.addForm['ext_' + index + '_' + id] = e.target.checked
        app.$set(this.addForm, `ext_${index}_${id}`, e.target.checked)
        app.extAmount = 0
        for (const k in app.zxData) {
          app.extAmount = app.extAmount + app.zxData[k].check_total
        }
        app.loading = false
      },
      clearColumn (index, id) {
        const app = this
        app.loading = true
        for (const k in app.addForm) {
          if (index === parseInt(k.match(/_(\S*)_/)[1])) {
            if (typeof app.addForm[k] === 'boolean') {
              app.addForm[k] = false
            }
            if (typeof app.addForm[k] === 'number') {
              app.addForm[k] = 0
              app.$set(this.addForm, k, 0)
            }
          }
        }
        app.zxData[index]['check_total'] = 0
        app.zxData[index]['ipt_total'] = 0
        setTimeout(() => {
          app.loading = false
        }, 1000)
      },
      delColumn (index) {
        const app = this
        const data = {}
        let total = 0
        app.loading = true
        if (app.zxData.length === 1) {
          app.$info({
            title: '当前增值项仅剩一条，无法继续删除',
            onOk: () => {
              app.loading = false
            }
          })
        } else {
          app.$confirm({
            title: '删除增项可能会导致业务数量发生变化',
            onOk: () => {
              for (const k in app.addForm) {
                if (index === parseInt(k.match(/_(\S*)_/)[1])) {
                  delete app.addForm[k]
                }
              }
              for (const k in app.zxData) {
                total += app.zxData[k].check_total + app.zxData[k].ipt_total
              }
              app.zxData.splice(index, 1)
              data['ext[values]'] = app.addForm
              data['ext[info]'] = app.zxData
              data['ext[price]'] = total
              postAddExtCache(data, app.cacheId, app.extCacheId).then(res => {
                if (res.status === 0) {
                  app.onCancel()
                  app.$emit('delete', data, app.businessId, app.cacheId, app.zxData.length)
                } else {
                  app.$warning({
                    title: res.msg
                  })
                }
              }).finally(() => {
                app.loading = false
              })
            }
          })
        }
      }
    }
  }
</script>

<style scoped>
  .total {
    font-weight: bold;
    font-size: 14px;
    color: #f00
  }
</style>
